package com.wxg.gui.table;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.table.AbstractTableModel;

import com.wxg.domain.table.TableDomain;

public class JDialogExample{
	
	private TableDomain tabledatas;
	
	private AbstractTableModel tableModel;

	private JDialog jdialog;
	
	private JPanel panel;
	
	private JButton btnDone;
	
	private JTextField nameTxtField = new JTextField();
	private JTextField ageTxtField = new JTextField();
	private JTextField msgTxtField = new JTextField();
	
	public JDialogExample(JFrame jframe, TableDomain tabledatas, AbstractTableModel tableModel){
		this.tabledatas = tabledatas;
		this.tableModel = tableModel;
		String title = "Add Table Row";
		boolean modal = true;
		jdialog = new JDialog(jframe, title, modal);
		jdialog.setSize(450, 180);
		jdialog.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
	}
	
	public void init(){
		panel = new JPanel(new GridLayout(3, 2));
		panel.add(new JLabel("Name: "));
		panel.add(nameTxtField);
		panel.add(new JLabel("Age: "));
		panel.add(ageTxtField);
		panel.add(new JLabel("Message: "));
		panel.add(msgTxtField);
		jdialog.add(panel, BorderLayout.CENTER);
		JPanel southPanel = new JPanel(new FlowLayout());
		btnDone = new JButton("Done!");
		southPanel.add(btnDone);
		jdialog.add(southPanel, BorderLayout.SOUTH);
		bindBtnEvent();
	}
	
	public void show(){
		nameTxtField.setText("");
		ageTxtField.setText("");
		msgTxtField.setText("");
		jdialog.setVisible(true);
	}
	
	private void bindBtnEvent(){
		btnDone.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				String name = nameTxtField.getText().trim();
				String age = ageTxtField.getText().trim();
				String msg = msgTxtField.getText().trim();
				if("".equals(name)){
					warning(nameTxtField, new Color(255, 255, 102));
					return;
				}
				if("".equals(age)){
					warning(ageTxtField, new Color(255, 255, 102));
					return;
				}
				if("".equals(msg)){
					warning(msgTxtField, new Color(255, 255, 102));
					return;
				}
				tabledatas.data(name, age, msg);
				tableModel.fireTableDataChanged();
				jdialog.setVisible(false);
			}
		});
	}
	
	private void warning(JTextField jtf, Color color){
		JTextField[] arr = {nameTxtField, ageTxtField, msgTxtField};
		for(JTextField f : arr){
			f.setBackground(new Color(255,255,255));
		}
		jtf.setBackground(color);
	}
}
